package cn.huijielong.modules.pay.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.huijielong.common.utils.RD;
import cn.huijielong.common.utils.VSUtil;
import cn.huijielong.modules.group.entity.OrderEntity;
import cn.huijielong.modules.group.entity.OrderItemEntity;
import cn.huijielong.modules.group.service.OrderService;
import cn.huijielong.modules.pay.service.PaymentService;
import cn.huijielong.modules.pub.entity.UserOpenidEntity;
import cn.huijielong.modules.pub.service.UserOpenidService;
import cn.huijielong.modules.sys.service.impl.SimpleServiceImpl;
import net.sf.json.JSONObject;

@Service("paymentService")
public class PaymentServiceImpl extends SimpleServiceImpl implements PaymentService {
	@Autowired
	private WXPayService wxPayService;
	@Autowired
	private UserOpenidService userOpenidService;
	@Autowired
	private OrderService orderService;
	
	@Override
	public RD unifinedOrder(Long buyUserId, JSONObject orderJson) {
		String orderNo=orderService.newOrderNo();
        BigDecimal payAmount=VSUtil.getDecimal(orderJson, "payAmount");
        int intAmount=payAmount.multiply(new BigDecimal(100)).intValue();
        if(intAmount<1) {
        	logger.error("用户{}，本次下单金额{}小于1分，不能下单",buyUserId,intAmount);
			return RD.error("金额不能少于1分，操作失败");
        }
        try {
	      //获取用户openid
	        UserOpenidEntity uoe=userOpenidService.queryObject(buyUserId);
	        if(uoe==null) {
	        	logger.error("用户{}，没有与小程序的关联openid，不能下单",buyUserId);
				return RD.error("会话失效，请重新登录再操作");
	        }
	        //微信支付下订单
	        Map<String,String> respData=wxPayService.unifinedOrder(uoe.getOpenid(), orderNo, intAmount);
			
			net.sf.json.JSONObject jsonOrder=orderJson.optJSONObject("orderInfo");
			net.sf.json.JSONArray jsonItemList=orderJson.optJSONArray("orderItemList");
			
			OrderEntity order=new OrderEntity();
			order.setThirdOrderNo(respData.get("prepay_id"));
			order.setOrderNo(orderNo);
			order.setBuyUserId(buyUserId);
			order.setGroupId(jsonOrder.optLong("groupId"));
			order.setMerchantId(jsonOrder.optLong("merchantId"));
			order.setPayAmount(payAmount);
			
			List<OrderItemEntity> itemList=new ArrayList<>();
			for(int i=0;i<jsonItemList.size();i++) {
				net.sf.json.JSONObject jsonGoods=jsonItemList.getJSONObject(i);
				OrderItemEntity orderItem=new OrderItemEntity();
				orderItem.setGoodsId(jsonGoods.optLong("goodsId"));
				orderItem.setGoodsName(jsonGoods.optString("name"));
				int buyNum=jsonGoods.optInt("buyNum");
				BigDecimal price=VSUtil.getDecimal(jsonGoods, "price");
				BigDecimal itemAmount=price.multiply(new BigDecimal(buyNum));
				orderItem.setBuyNum(buyNum);
				orderItem.setPayAmount(itemAmount);
				itemList.add(orderItem);
			}
			order.setOrderItemList(itemList);
			orderService.save(order);
		
			Map<String,String> payinfo=wxPayService.fillResponseData(respData);
			return RD.ok().put("payinfo", payinfo);
		} catch (Exception e) {
			logger.error("下单失败：",e);
			return RD.error("系统故障，请稍后再试");
		}
	}

	@Override
	public void trade(String orderNo) {
		orderService.updateSuccess(orderNo);
	}


}
